package com.example.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.Configuration;
import com.example.bean.Order;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.omg.CORBA.Any;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;


/**
 * HttpClient工具类
 *
 * @author ZhangYuanqiang
 * @since 2021-06-10
 */
public class HttpUtils {

    /**
     * 字符编码
     */
    private final static String UTF8 = "utf-8";
    /**
     * 字节流数组大小（1MB）
     */
    private final static int BYTE_ARRAY_LENGTH = 1024 * 1024;

    /**
     * 基础GET方法 使用默认的Headers
     * @param url
     * @return
     */
    public static String get(String url){
       return get(url,null);
    }

    /**
     * 发起get请求支持传入headers
     * @param url
     * @param headers
     * @return
     */
    public  static String get(String url,Map<String,String> headers){
        HttpEntity httpEntity = null;
        String str = null;
        //创建可关闭的http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpUtils.headersHandler(httpGet,headers);
        //设置接收response的对象
        CloseableHttpResponse httpResponse = null;
        try{
            //执行请求
            httpResponse = client.execute(httpGet);
            //解析响应体
            httpEntity = httpResponse.getEntity();
            str = EntityUtils.toString(httpEntity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(httpResponse != null){
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (client != null) {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return str;
    }

    /**
     * 设置请求头
     * @param httpUri http请求类
     * @param headers 需要添加的请求头
     */
    private  static void headersHandler(HttpUriRequest httpUri,Map<String,String> headers){
        // 设置长连接
        httpUri.setHeader("Connection", "keep-alive");
        // 设置代理（模拟浏览器版本）
        httpUri.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        if(headers != null){
            for(Map.Entry<String,String> entry : headers.entrySet()){
                String key = entry.getKey();
                String value = entry.getValue();
                //设置headers
                httpUri.setHeader(key,value);
            }
        }
    }
//
//    public static <AnyType> AnyType parseData(){
//        //处理为JSON格式的数据
//        JSONObject jsonObject = JSONObject.parseObject(str);
//        //拿到code 和 status
//        Integer code = (Integer) jsonObject.get("code");
//        String status = jsonObject.getString("status");
//        if(code == 200 && status.equals("success")){
//            String data = jsonObject.getString("data");
//            //解析为Order对象
//            Order order  = JSON.parseObject(data,Order.class);
//            //查看结果
//            String orderStr = order.toString();
//            System.out.println(orderStr);
//            //处理文件
//            //this.fineHandler(order.getFiles());
//        }
//
//    }

    /**
     * 下载文件
     * @param url 文件地址
     * @param path 存储地址
     * @param fileName 保存名称
     * @return 返回文件存储路径
     */
    public static String download(String url,String path,String fileName){
        HttpGet httpGet = new HttpGet(url);
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String filePath = null;
        if(Objects.isNull(path) || path.isEmpty()){
            filePath = fileName;
        }else{
            if (path.endsWith("/")) {
                filePath = path + fileName;
            } else {
                filePath = path + "/" + fileName;
            }
        }
        File file = new File(filePath);
        if(!file.exists()){
            try{
                file.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        try (FileOutputStream fos = new FileOutputStream(file); InputStream in = getRespInputStream(httpGet, null)) {
            if (Objects.isNull(in)) {
                return null;
            }
            byte[] bytes = new byte[BYTE_ARRAY_LENGTH];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 获取HTTP输入流
     * @param request
     * @param headers
     * @return
     */
    private static InputStream getRespInputStream(HttpGet request, Map<String, String> headers) {
        // 设置请求头
        headersHandler(request, headers);
        // 获取响应对象
        HttpResponse response = null;
        try {
            response = HttpClients.createDefault().execute(request);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // 获取Entity对象
        HttpEntity entity = response.getEntity();
        // 获取响应信息流
        InputStream in = null;
        if (Objects.nonNull(entity)) {
            try {
                in = entity.getContent();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return in;
    }

    /**
     * 发起POST 请求使用默认请求头
     * @param url 请求url
     * @param params 请求携带的参数
     * @return 返回获取到的数据实体
     */
    public static String post(String url, List<BasicNameValuePair> params){
        return post(url,null,params);
    }

    /**
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String post(String url,Map<String,String> headers,List<BasicNameValuePair> params){
        // 创建 HttpClient 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        HttpEntity httpEntity = null;
        String str = null;
        // 设置长连接
        httpPost.setHeader("Connection", "keep-alive");
        // 设置代理（模拟浏览器版本）
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        if(headers != null){
            for(Map.Entry<String,String> entry : headers.entrySet()){
                String key = entry.getKey();
                String value = entry.getValue();
                //设置headers
                httpPost.setHeader(key,value);
            }
        }
        CloseableHttpResponse httpResponse = null;
        try{
            // 设置 HttpPost 参数
            httpPost.setEntity(new UrlEncodedFormEntity(params, UTF8));
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            str = EntityUtils.toString(httpEntity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 校验HTTP请求是否成功 主要校验status和code 字段
     * @return
     */
    public static boolean checkRsponse(String httpEntity){
        if(httpEntity == null){
            return false;
        }
        boolean flag = false;
        try{
            //处理为JSON格式的数据
            JSONObject jsonObject = JSONObject.parseObject(httpEntity);
            //拿到code 和 status
            Integer code = (Integer) jsonObject.get("code");
            String status = jsonObject.getString("status");
            if(code == 200 && status.equals("success")){
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 将后台返回的数据处理为JSON格式的数据
     * @param httpEntity
     * @return
     */
    public static JSONObject parseResponse(String httpEntity){
        if(httpEntity == null){
            return null;
        }
        JSONObject jsonObject = null;
        try{
            //处理为JSON格式的数据
            jsonObject = JSONObject.parseObject(httpEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 将response 数据包中的data解析为JSONOBJECT
     * @param jsonObject
     * @return
     */
    public static JSONObject parseResponse(JSONObject jsonObject){
        if(jsonObject == null){
            return null;
        }
        JSONObject object = null;
        try{
            String data = jsonObject.getString("data");
            object = JSONObject.parseObject(data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return object;
    }
}